package prome

import (
	"strings"
	"time"

	"github.com/prometheus/client_golang/prometheus"
)

// prmethous监控变量
var (
	requestCounter    *prometheus.CounterVec
	durationHistogram *prometheus.HistogramVec
)

// InitPrometheus 初始化Prometheus
func InitPrometheus(space, name string) {
	if strings.Contains(name, "-") {
		name = strings.ReplaceAll(name, "-", "_")
	}
	requestCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: space,
			Subsystem: name,
			Name:      "request_total",
			Help:      "The total number of processed requests",
		},
		[]string{"service"},
	)
	prometheus.MustRegister(requestCounter)
	durationHistogram = prometheus.NewHistogramVec(
		prometheus.HistogramOpts{
			Namespace: space,
			Subsystem: name,
			Name:      "duration_sec",
			Help:      "server requests duration(sec).",
			Buckets:   []float64{0.05, 0.1, 0.25, 0.5, 1, 1.5, 2, 5},
		},
		[]string{"service"},
	)
	prometheus.MustRegister(durationHistogram)
}

// PromeTrace promethous数据记录
func PromeTrace(label string) func() {
	start := time.Now()
	return func() {
		if requestCounter != nil {
			requestCounter.WithLabelValues(label).Inc()
		}
		if durationHistogram != nil {
			durationHistogram.WithLabelValues(label).Observe(time.Since(start).Seconds())
		}
	}
}
